# -*- coding: utf-8 -*-

from dtcloud.fields import Command
from .One2ManyConvert import One2ManyConvert


class Many2ManyConvert(One2ManyConvert):
    field_type = 'many2many'

    @classmethod
    def to_field(cls, value, metadata=None, update=False):
        if isinstance(value, str):
            data_rec = value.split(',') if ',' in value else [value]
        elif isinstance(value, int):
            data_rec = [value]
        else:
            data_rec = value

        try:
            if isinstance(data_rec, tuple) or isinstance(data_rec, list):
                return [Command.set([int(d) for d in data_rec])]
        except Exception as e:
            raise ValueError(f'{e.args}')

    @classmethod
    def to_domain(cls, field, value, **kwargs):
        if isinstance(value, str):
            data_rec = value.split(',') if ',' in value else [value]
        elif isinstance(value, int):
            data_rec = [value]
        else:
            data_rec = value

        try:
            if isinstance(data_rec, tuple) or isinstance(data_rec, list):
                return [(field.name, 'in', [int(d) for d in data_rec])]
        except Exception as e:
            raise ValueError(f'{e.args}')
